import React from 'react';
import { Tabs, Button, Popconfirm, Table, Typography, Tooltip, Spin, message, Alert, Row, Col, Empty } from 'antd';
import { BottomAction } from '@/components';
import { router, withRouter } from 'umi';
import LabelValue from '@/components/LabelValue';
import FunctionSelector from '@/pages/Setting/Privilege/components/FunctionSelector';
import { Icon } from '@/pages/Setting/Privilege/components/PrivilegeIcon';
import { useRequest, defaultFormatResult } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import { createDictionary } from '@/dictionary';
import { size } from 'lodash';
import { guid } from '@/utils/utils';
import moment from 'moment';
import { hasWorkFlowByType, gotoWorkFlowDetail } from '@/pages/WorkFlow/utils';
import authHelper from '@/utils/auth/helper';
import styles from '../Edit/index.less';
import { getPrivilegeTemplateDetail, deleteRoleInSubmitMode } from '../../services';

const { checkCode } = authHelper;

const { TabPane } = Tabs;
const { Paragraph } = Typography;

const [, getOrgOptionText] = createDictionary('PRIVILEGE_TEMPLATE_ORG_SCOPE');
const [, getCompanyOptionText] = createDictionary('PRIVILEGE_TEMPLATE_COMPANY_SCOPE');
const [, getShowStatusText] = createDictionary('PROVILEGE_TEMPLATE_SHOW_STATUS');

// 权限管理-模板详情
const Info = ({ location }) => {
    const { query } = location;

    // 模板分组字典数据
    const [, getRoleModuleTypeText] = useDictionary('roleModuleType');

    // 获取详情
    const { data, loading } = useRequest(() => getPrivilegeTemplateDetail(query?.code), {
        ...defaultFormatResult
    });

    // 删除模板
    const { run: deleteRun, loading: deleteLoading } = useRequest(param => deleteRoleInSubmitMode(param), {
        manual: true
    });

    const {
        code,
        nameZh,
        nameEn,
        type,
        icon,
        remarkEn,
        remarkZh,
        showStatus, // 显示的状态值 0=待审核,1=审批中,2=审核通过,3=驳回,-998=角色模板已生效，编辑模板保存的草稿,-999=角色模板未生效，新增模板保存的草稿"
        authorityList = [],
        dataScopeSetType,
        authorityDataList = [],
        dutyGroupList = [],
        dutyQuantity,
        draftTime,
        auditCode,
        auditEnable // 审批模板启用状态
    } = data || {};
    // 全局统一的数据！！后端是说拿数组第一项！！
    const globalDataScopeSetType = size(authorityDataList) > 0 ? authorityDataList[0] : {};

    // tab头部重写
    const renderTabBar = (props, DefaultTabBar) => (
        <div className={styles.tabBar}>
            <div className={styles.tabBarName}>模板详情</div>
            <DefaultTabBar {...props} style={{ flex: 1 }} />
        </div>
    );

    const columns = [
        {
            title: '功能模块',
            dataIndex: 'resourceModuleNameZh',
            width: 150,
            render: text => (
                <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 0 }}>
                    <Tooltip title={text}>{text}</Tooltip>
                </Paragraph>
            )
        },
        {
            title: '介绍',
            dataIndex: 'resourceModuleRemarkZh',
            width: 373,
            render: text => (
                <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 0 }}>
                    <Tooltip title={text}>{text}</Tooltip>
                </Paragraph>
            )
        },
        {
            title: '组织机构权限',
            dataIndex: 'orgList',
            width: 220,
            render: (text, record) => (
                <>
                    <div>{getOrgOptionText(record?.organizationalScope)}</div>
                    {size(text) > 0 && (
                        <Paragraph ellipsis={{ rows: 3, expandable: true }}>
                            <div>
                                {size(text) > 0 &&
                                    text.map((item, index) => (
                                        <span key={item?.orgCode} style={{ marginRight: 5 }}>
                                            <Tooltip title={item?.orgFullName}>{item?.orgName}</Tooltip>
                                            {size(text) !== index + 1 && '、'}
                                        </span>
                                    ))}
                            </div>
                        </Paragraph>
                    )}
                </>
            )
        },
        {
            title: '行政机构权限',
            dataIndex: 'companyList',
            width: 220,
            render: (text, record) => (
                <>
                    <div>{getCompanyOptionText(record?.administrativeScope)}</div>
                    {size(text) > 0 && (
                        <Paragraph ellipsis={{ rows: 3, expandable: true }}>
                            <div>
                                {size(text) > 0 &&
                                    text.map((item, index) => (
                                        <span key={item?.companyCode} style={{ marginRight: 5 }}>
                                            <Tooltip title={item?.companyFullName}>{item?.companyName}</Tooltip>
                                            {size(text) !== index + 1 && '、'}
                                        </span>
                                    ))}
                            </div>
                        </Paragraph>
                    )}
                </>
            )
        }
    ];

    // tab配置
    const formTabPaneArray = [
        {
            name: '基础设置',
            component: (
                <div style={{ marginTop: 12 }}>
                    <LabelValue label="模板名称(中文)" value={nameZh} />
                    <LabelValue label="模板名称(英文)" value={nameEn} />
                    <LabelValue label="模板分组" value={() => <div>{getRoleModuleTypeText(type || '')}</div>} />
                    <LabelValue label="模版图标" labelAlignItems="center" value={() => <Icon icon={icon} />} />
                    <LabelValue
                        label="模板简介(中文)"
                        value={remarkZh}
                        style={{ alignItems: 'flex-start', maxWidth: '85%' }}
                    />
                    <LabelValue
                        label="模板简介(英文)"
                        value={remarkEn}
                        style={{ alignItems: 'flex-start', maxWidth: '85%', wordWrap: 'break-word' }}
                    />
                    <LabelValue
                        label="模板状态"
                        value={() =>
                            showStatus === 1 ? (
                                <Button
                                    type="link"
                                    style={{ padding: 0, margin: 0, height: 'auto' }}
                                    onClick={() => {
                                        history.push(gotoWorkFlowDetail(auditCode));
                                    }}
                                >
                                    {getShowStatusText(showStatus)}
                                </Button>
                            ) : (
                                getShowStatusText(showStatus)
                            )
                        }
                    />
                    {size(draftTime) > 0 && (
                        <LabelValue label="上次编辑时间" value={moment(draftTime).format('YYYY-MM-DD HH:mm')} />
                    )}

                    {auditEnable === true && showStatus === 1 && (
                        <Alert
                            message={<>当前显示原有模板信息，另外存在正在审批中的新模板</>}
                            type="warning"
                            closable
                            style={{ marginBottom: 20 }}
                        />
                    )}
                </div>
            )
        },
        {
            name: '功能权限',
            component: (
                <div style={{ marginTop: 12 }}>
                    <FunctionSelector disabled value={authorityList} isShow />
                </div>
            )
        },
        {
            name: '数据权限',
            component: (
                <div style={{ marginTop: 12 }}>
                    <LabelValue
                        label="数据权限"
                        labelInline={dataScopeSetType === 1}
                        value={() => (
                            <div>
                                {dataScopeSetType === 0 && '全局统一'}
                                {dataScopeSetType === 1 && '模块控制'}
                            </div>
                        )}
                    />
                    {/* 全局统一 */}
                    {dataScopeSetType === 0 && (
                        <>
                            <div>
                                <LabelValue
                                    label="组织机构权限"
                                    value={getOrgOptionText(globalDataScopeSetType?.organizationalScope)}
                                />
                                <div style={{ margin: '0 0 18px 135px ', color: 'rgba(0, 0, 0, 0.85)' }}>
                                    {size(globalDataScopeSetType.orgList) > 0 &&
                                        globalDataScopeSetType.orgList.map((item, index) => (
                                            <span key={item?.orgCode} style={{ marginRight: 5 }}>
                                                <Tooltip title={item?.orgFullName}>{item?.orgName}</Tooltip>
                                                {size(globalDataScopeSetType.orgList) !== index + 1 && '、'}
                                            </span>
                                        ))}
                                </div>
                            </div>
                            <div>
                                <LabelValue
                                    label="行政机构权限"
                                    value={getCompanyOptionText(globalDataScopeSetType?.administrativeScope)}
                                />
                                <div style={{ margin: '0 0 18px 135px ', color: 'rgba(0, 0, 0, 0.85)' }}>
                                    {size(globalDataScopeSetType.companyList) > 0 &&
                                        globalDataScopeSetType.companyList.map((item, index) => (
                                            <span key={item?.companyCode} style={{ marginRight: 5 }}>
                                                <Tooltip title={item?.companyFullName}>{item?.companyName}</Tooltip>
                                                {size(globalDataScopeSetType.companyList) !== index + 1 && '、'}
                                            </span>
                                        ))}
                                </div>
                            </div>
                        </>
                    )}

                    {/* 模块控制 */}
                    {dataScopeSetType === 1 && (
                        <Table
                            style={{ marginTop: 26 }}
                            dataSource={authorityDataList}
                            columns={columns}
                            pagination={false}
                            rowKey="resourceModuleCode"
                        />
                    )}
                </div>
            )
        },
        {
            name: '授权岗位',
            component: (
                <div style={{ marginTop: 12 }}>
                    <LabelValue label="已授权岗位" labelInline value={() => <span>{dutyQuantity}</span>} />
                    <Row>
                        <Col md={24} lg={12}>
                            {size(dutyGroupList) > 0 ? (
                                <div className={styles.postTabpaneBox}>
                                    {dutyGroupList.map(item => (
                                        <div className={styles.list} key={item?.orgCode}>
                                            <div className={styles.orgName}>{item?.orgName}</div>
                                            <div className={styles.orgList}>
                                                {item?.dutyNameList.map(subItem => {
                                                    const key = guid();
                                                    return (
                                                        <Tooltip title={item?.orgFullName} key={key}>
                                                            <span>{subItem}</span>
                                                        </Tooltip>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <div
                                    style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                                >
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
                                </div>
                            )}
                        </Col>
                    </Row>
                </div>
            )
        }
    ];

    return (
        <div className={styles.templateEditTabsWrap}>
            <Spin spinning={loading}>
                <Tabs size="large" defaultActiveKey="1" tabBarGutter={64} renderTabBar={renderTabBar}>
                    {formTabPaneArray.map((item, index) => (
                        <TabPane
                            forceRender
                            tab={
                                <div className={styles.tabBarStep}>
                                    <span className={styles.num}>{index + 1}</span>
                                    {item.name}
                                </div>
                            }
                            key={String(index + 1)}
                        >
                            {item.component}
                        </TabPane>
                    ))}
                </Tabs>

                <BottomAction>
                    <Popconfirm
                        title={`确定要删除${nameZh}？`}
                        onConfirm={async () => {
                            if (showStatus === 2) {
                                // 校验流程是否存在
                                const { workFlowUrl } = await hasWorkFlowByType('PrivilegeTemplateApply');
                                if (workFlowUrl) {
                                    const { data: id, code: resultCode, msg } = await deleteRun(code);
                                    if (resultCode === 10000) {
                                        history.push(`${workFlowUrl}${id}`);
                                    } else {
                                        message.error(msg);
                                    }
                                }
                            } else {
                                // 如果是草稿或其他状态不走流程校验
                                const { code: resultCode, msg } = await deleteRun(code);
                                if (resultCode === 10000) {
                                    message.success(msg);
                                    history.push('/setting/privilege/templatemanagement');
                                } else {
                                    message.error(msg);
                                }
                            }
                        }}
                        placement="topRight"
                        okText="确认"
                        cancelText="取消"
                        disabled={showStatus === 1 || !checkCode('system:authorization:role:delete')}
                    >
                        <Button
                            type="dashed"
                            loading={deleteLoading}
                            disabled={showStatus === 1 || !checkCode('system:authorization:role:delete')}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                    <Button
                        disabled={!checkCode('system:authorization:role:copy')}
                        onClick={() => {
                            history.push({
                                pathname: '/setting/privilege/copytemplate',
                                query: { code, actionType: 'copy' }
                            });
                        }}
                    >
                        复制
                    </Button>
                    <Button
                        disabled={showStatus === 1 || !checkCode('system:authorization:role:edit')}
                        type="primary"
                        onClick={() => {
                            history.push({
                                pathname: '/setting/privilege/edittemplate',
                                query: { code }
                            });
                        }}
                    >
                        编辑模板
                    </Button>
                </BottomAction>
            </Spin>
        </div>
    );
};

export default withRouter(Info);
